module.exports = app => {
  const jwt = require('jsonwebtoken')
  const assert = require('http-assert')
  const AdminUser = require('../../models/AdminUser')

  app.post('/admin/api/login', async(req, res) => {
    const { name, pwd } = req.body
    // 1.根据用户名找用户
    const user = await AdminUser.findOne({name}).select('+pwd')
    assert(user, 422, '用户不存在')
    // 2.校验密码
    const isValid = require('bcrypt').compareSync(pwd, user.pwd)
    assert(isValid, 422, '密码错误')
    // 3.返回token
    const token = jwt.sign({ id: user._id }, app.get('secret'))
    res.send({token})
  })
}